//
// Created by 31951 on 2020/11/5.
//

#include "ScreenShot.h"
#include "PartialShot.h"

ScreenShot::ScreenShot(QWidget *parent)
        : QWidget(parent) {
    // 去除任务栏图标
//    this->setWindowFlags(Qt::WindowType::Tool);

    auto lay = new QHBoxLayout(this);
    setLayout(lay);
    lay->addWidget(full);
    lay->addWidget(partial);

    connect(partial, &QPushButton::clicked, this, &ScreenShot::handlePartScreen);
    connect(full, &QPushButton::clicked, this, &ScreenShot::handleFullScreen);
}

void ScreenShot::handleFullScreen() {
    // 最小化屏幕
    this->hide();
    postpone(250);
    // 截图
    auto screen_image = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId());
    auto save_file_name = QFileDialog::getSaveFileName(this, tr("文件另存为"));
    if (!save_file_name.isEmpty()) screen_image.save(save_file_name);

}

void ScreenShot::handlePartScreen() {
    // 最小化屏幕
    this->hide();
    //延时等待父窗体最小化 延时250毫秒
    postpone(250);
    // 截图
    auto screen_image = QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId());
    auto partial_shot = new PartialShot;
    partial_shot->setScreenImage(screen_image);
    partial_shot->showFullScreen();

}

void ScreenShot::postpone(int msecs) {
    auto time = QTime::currentTime().addMSecs(msecs);
    while (QTime::currentTime() < time)
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

}
